
###############################################################################
# client-python.py
# Name:ZYM
# NetId:10235101501
###############################################################################
import sys
import os
import socket

SEND_BUFFER_SIZE = 2048
def client(server_ip, server_port):
    """TODO: Open socket and send message from sys.stdin"""
    HOST, PORT = server_ip, server_port
    s=None
    for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        try:
            s = socket.socket(af, socktype, proto)
        except OSError as msg:
            s = None
            continue
        try:
            s.connect(sa)
        except OSError as msg:
            s.close()
            s = None
            continue
        break
    if s is None:
        print ('could not open socket')
        sys.exit(1)

    while 1:
        data = os.read(0,SEND_BUFFER_SIZE)
        if not data:
            break
        s.send(data)
    s.close()


def main():
    """Parse command-line arguments and call client function """
    if len(sys.argv) != 3:
        sys.exit("Usage: python client-python.py [Server IP] [Server Port] < [message]")
    server_ip = sys.argv[1]
    server_port = int(sys.argv[2])
    # print(server_ip, server_port)
    client(server_ip, server_port)

if __name__ == "__main__":
    main()

